import sqlite3 as sqlite
import logging
from pyhildonmemer import commons

class Config(object):
    DEFAULTS = {\
        "services":["from services import memer"],\
        "logins":[commons.Login()],\
        "refreshTime":"60",\
        "logging": logging.DEBUG}
    instance = None
    def __init__(self, arch = None):
        self.arch = arch
        logging.debug("start config")

    def canSave(self):
        return 0

    def init(self):
        pass

    def close(self):
        pass

    def getAttr(self, attr):
        return None

    def setAttr(self, attr, val = None):
        pass

    def getLogins(self):
        return None

    def setLogin(self, service, login = "", passwd = ""):
        pass

    def getServices(self):
        return None

    def setService(self, service):
        pass

    @staticmethod
    def install(arch = None, srvs = [], sortedTypes = []):
        for cfgType in sortedTypes:
            try:
                cfgType.install(arch, srvs)
                logging.debug("install config type: %s " % str(cfgType))
                break
            except:
                pass

    @staticmethod
    def getInstance(arch = None, sortedTypes = []):
        if Config.instance == None:
            for cfgType in sortedTypes:
                try:
                    cfg = cfgType(arch)
                    cfg.init()
                    Config.instance = cfg
                    logging.debug("used config type: %s " % str(cfgType))
                    return cfg;
                except:
                    pass
            cfg = ConfigWithoutFile(arch)
            logging.debug("used config type: %s " % str(ConfigWithoutFile))
            Config.instance = cfg
            return cfg
        return instance

    def close(self):
        pass

    def save(self, arch = None):
        pass

class ConfigWithoutFile(Config):
    def __init__(self, arch = None):
        self.cfgs = Config.DEFAULTS
        super(ConfigWithoutFile, self).__init__(arch)

    def getAttr(self, name):
        if self.cfgs.has_key(name):
            return self.cfgs[name]
        return None

    def setAttr(self, name, val = None):
        if self.cfgs.has_key(name):
            self.cfgs[name] = val

    def getLogins(self):
        return self.getAttr("logins")

    def setLogin(self, service, login = None, passwd = None):
        user = commons.Profile("me", login, passwd = passwd)
        user.setService(service)
        self.cfgs["logins"]

    def getServices(self):
        return self.cfgs["services"]

logging.basicConfig(level=Config.DEFAULTS["logging"])

class ConfigSqlite(Config):
    def __init__(self, arch):
        self.sql = None
        self.cursor = None
        super(ConfigSqlite, self).__init__(arch)

    def canSave(self):
        return 1

    def init():
        try:
            self.sql = sqlite.connect(self.arch)
        except:
            logging.error("can't connect to: %s " % str(self.arch))
            return None
        cursor = self.sql.cursor()
        return cursor

    @staticmethod
    def install (arch, srv = [], sortedTypes = []):
        sql = sqlite.connect(arch,)
        cursor = sql.cursor()
        cursor.execute('create table logins (login text, passwd text, service text)')
        cursor.execute('create table configs (key text, value text)')
        cursor.execute('create table srvs (import text)')
        cursor.commit()
        [cursor.execute("insert into srvs values (?)", (sv)) for sv in srv]
        cursor.commit()

    def getServices(self):
        self.cursor.execute("select import from srvs");
        SERVICE_COL = 0
        return [row[SERVICE_COL] for row in self.cursor]

    def setService(self, service):
        self.cursor.execute("insert into srvs values(?)", service)

    def getLogins(self, servs = []):
        where = ""
        if len(servs) > 0:
            where = "where service in ("
            sep = ""
            for serv in servs:
                where += "%s?" % sep
                sep = ","
            where += ")"
        self.cursor.execute("select service, login, passwd from logins %s" %(where), servs)
        SERVICE_COL = 0
        LOGIN_COL = 1
        KEY_COL = 2
        return [commons.Login(login[SERVICE_COL], login[SERVICE_COL], login[KEY_COL]) for login in self.cursor]

    def setLogin(self, login):
       self.cursor.execute("REPLACE into logins values (?,?,?)", (login.getLogin, login.getPasswd, login.setService))
       self.cursor.commit()

    def close(self):
        self.sql.close()